import {Component, OnInit, ViewChild} from '@angular/core';
import {Observable} from 'rxjs/index';
import {NavController, ToastController} from '@ionic/angular';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {HttpService} from '../../services/http.service';
import {BasePage} from '../../common/basePage';

/**
 * 用户借款－还款计划
 */
@Component({
  selector: 'app-user-loan-plan',
  templateUrl: './user-loan-plan.page.html',
  styleUrls: ['./user-loan-plan.page.scss'],
})
export class UserLoanPlanPage extends BasePage implements OnInit {

  @ViewChild('infiniteScroll') infiniteScroll;
  // 分页及ID参数
  public condition: any = {
    currPage: 1, // 当前页码
    pageSize: 20 // 每页数据条数
  };

  public dataList: any[] = [];

  constructor(public navCtrl: NavController,
              public toastCtrl: ToastController,
              private service$: HttpService
  ) {
    super(navCtrl, toastCtrl);
  }

  ngOnInit() {
    this.getDataList()
      .subscribe(obj => {
        this.handler(obj);
      });
  }

  private getDataList(): Observable<any> {
    return this.service$.doRequest(UrlAndOPT.auth_loan_plan, this.condition);
  }

  private handler(obj) {
    if (obj && obj['obj']) {
      const records = obj['obj'];
      this.condition = {...this.condition, currPage: records['currPage'], pageSize: records['pageSize']};
      this.dataList = records['page'];
      // 根据列表长度判断是否禁用加载
      this.infiniteScroll.disabled = this.dataList.length === records['totalCount'];
    } else {
      this.infiniteScroll.disabled = true;
    }
  }

  // 下拉刷新列表
  doRefresh(event?) {
    this.condition.currPage = 1;
    this.getDataList()
      .subscribe(obj => {
        this.handler(obj);
        if (event) {  // 如果为下拉刷新，关闭下拉组件
          event.target.complete();
        }
      });
  }

  // 上拉加载更多
  loadMoreData(event) {
    this.condition.currPage++;
    this.getDataList()
      .subscribe(obj => {
        if (obj && obj['records']) {
          const records = obj.records;
          // 累加数据
          this.dataList = [...this.dataList, ...records['page']];
          // 根据列表长度判断是否禁用加载
          this.infiniteScroll.disabled = this.dataList.length === records['totalCount'];
        }
        // 关闭上拉组件
        event.target.complete();
      });
  }

  // 前往出借账单详情
  pushDetail(data) {
    this.navCtrl.navigateForward(['/auth/user-loan-bill-detail', {data: JSON.stringify(data)}]);
  }

  goBack() {
    this.navCtrl.navigateBack(['/tabs/user']);
  }

}
